-module(sample_client).

%%-behaviour(my_websocket_client).

-include("common.hrl").

-define(state,state).
-record(state,{
    index = 1,%%启动的网关序号，启动后要增加序号
    gateway_list=[],%%存储这里启动的客户端网关序号列表，未分配的
    account_list=[]%%玩家accountID对应网关序号
}).

-export([start/0,login/1]).
-export([dropFangKuoHao/1]).

%% websocket specific callbacks
-export([onmessage/1,onopen/0,onclose/0,close/0]).

%%=============================EXPORTED FUNCTION=====================================
start() ->
    OldList = getStateElement(#state.gateway_list,[]),
    Index = getStateElement(#state.index,1),
    {ok,Pid}=my_websocket_client:start(Index,"localhost",8002,?MODULE),
    setStateElement(#state.gateway_list,[Index|OldList]),
    setStateElement(#state.index,Index+1),
    Pid.

login(AccountID) ->
    %%分配一个网关序号
    [Index|T] = getStateElement(#state.gateway_list,[]),
    setStateElement(#state.gateway_list,T),
    List = getStateElement(#state.account_list,[]),
    List1 = lists:keystore(AccountID,1,List,{AccountID,Index}),
    setStateElement(#state.account_list,List1),
    Msg = "[10001,"++integer_to_list(AccountID)++",\"role_"++integer_to_list(AccountID)++"\",\"none\"]",
    send(Index, Msg).

onmessage(Data) ->
%%    Data1 = mochijson2:decode(Data),
%%    Data2 = lists:nth(2,Data1),
%%    ?DEBUG("onmessage Data 3333333=~p",[Data2]),
%%    Data3 = dropFangKuoHao(Data2),
%%    ?DEBUG("onmessage Data 444444444=~p",[Data3]),
%%    Decode = proto:decode2(Data3),
%%    ?DEBUG("decode Data = ~p",[Decode]),
    ok.

onclose() ->
    io:format("Connection closed~n").

onopen() ->
    io:format("Connection open~n"),
    ok.

close() ->
    my_websocket_client:close().

%%=============================LOCAL FUNCTION=====================================
send(Index, Data) ->
    io:format("client send Index=~p, Data = ~p~n",[Index, Data]),
    my_websocket_client:write(Index, Data).

getStateElement(Index,DefaultValue) ->
    case get(?state) of
        #state{}=State -> element(Index,State);
        _ -> DefaultValue
    end.
setStateElement(Index,Value) ->
    State1 = case get(?state) of
        #state{}=State -> setelement(Index,State,Value);
        _ -> setelement(Index,#state{},Value)
    end,
    put(?state,State1).

dropFangKuoHao(List) ->
    dropFangKuoHao_1(List,[]).
dropFangKuoHao_1([],R) -> lists:reverse(R);
dropFangKuoHao_1([[List]|T],R)when is_list(List) ->
    Child = dropFangKuoHao_1(List,[]),
    dropFangKuoHao_1(T,[Child|R]);
dropFangKuoHao_1([[Value]|T],R) ->
    dropFangKuoHao_1(T,[Value|R]);
dropFangKuoHao_1([Value|T],R) ->
    dropFangKuoHao_1(T,[Value|R]).